from django.core.paginator import Paginator
from ...utils.time_conversion import datetime_to_times


def check_thumb_img(dalljob_mes):
    '''
    判断图片是否有缩略图
    '''
    if dalljob_mes.thumburl:
        return dalljob_mes.thumburl
    else:
        return dalljob_mes.imgurl


# 获取任务
def get_dalljob_handler(all_user_dalljob, page, page_size):
    tree = []

    paginator = Paginator(all_user_dalljob, int(page_size))
    # 获取总页数
    total_pages = paginator.num_pages

    if int(page) > total_pages:
        # 如果请求的页数大于总页数 那就返回空
        return tree
    else:
        page_obj = paginator.get_page(int(page))

    # 整合数据
    for dalljob_mes in page_obj:
        tree.append({
            "id": dalljob_mes.id,
            "user_id": dalljob_mes.user_id,
            "prompt": dalljob_mes.prompt,
            "img_url": dalljob_mes.imgurl,
            "thumb_url": check_thumb_img(dalljob_mes),
            "org_url": dalljob_mes.orgurl,
            "publish": dalljob_mes.publish,
            "power": dalljob_mes.power,
            "progress": dalljob_mes.progress,
            "err_msg": dalljob_mes.errmsg,
            "created_at": datetime_to_times(dalljob_mes.created_at),
        })

    return tree
